<?php

declare(strict_types=1);
/**
 * Created by .
 * User: luogan
 * Date: 2021/12/22
 */

namespace App\Exception\Handler;


use App\Exception\AuthException;
use App\Exception\TokenException;
use App\Exception\ValidationException;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use App\Exception\ErrorException;
use Hyperf\Logger\LoggerFactory;
use Throwable;

class ErrorExceptionHandler extends ExceptionHandler
{

    protected $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        // 捕获异常
        if ($throwable instanceof TokenException || $throwable instanceof AuthException || $throwable instanceof ValidationException || $throwable instanceof ErrorException) {
            // 格式化输出
            $data = api($throwable->getMessage(),[],$throwable->getCode());
            // 阻止异常冒泡
            $this->stopPropagation();
            $this->logger->info($throwable->getMessage());
            return $response->withStatus(500)->withBody(new SwooleStream($data));
        }
        // 交给下一个异常处理器
        return $response;
        // 或者不做处理直接屏蔽异常
    }

    /**
     * 判断该异常处理器是否要对该异常进行处理
     */
    public function isValid(Throwable $throwable): bool
    {
        return true;
    }

    public function returnException($message,$code,ResponseInterface $response)
    {
        // 格式化输出
        $data = api($message,[],$code);
        // 阻止异常冒泡
        $this->stopPropagation();
        return $response->withStatus(500)->withBody(new SwooleStream($data));
    }
}
